﻿using SqlSugar;
using StoreSQLSugar_.DBUtility;
using StoreSQLSugar.Models;
using StoreSQLSugar.Models.ViewModel;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace StoreSQLSugar.Forms.UserFrm
{
    public partial class UserListFrm : UserControl
    {
        DateTimePicker dtStartTime = null;
        DateTimePicker dtEndTime = null;
        TextBox txtCondition = null;
        public UserListFrm()
        {
            InitializeComponent();

            Load += UserListFrm_Load;
            cbbSearchCondition.SelectedIndexChanged += cbbSearchCondition_SelectedIndexChanged;
            btnSearch.Click += btnSearch_Click;
            btnAdd.Click += btnAdd_Click;
            btnUpdate.Click += btnUpdate_Click;
            btnDelete.Click += btnDelete_Click;
            btnEnabled.Click += btnEnabled_Click;
            dataGridView1.CellFormatting += dataGridView1_CellFormatting;
            ucPager1.PageChanged += UcPager1_PageChanged;
        }

        private void UserListFrm_Load(object sender, EventArgs e)
        {
            cbbSearchCondition.SelectedIndex = 0;
            ucPager1.Page = 1;
        }

        private void UcPager1_PageChanged(object sender, EventArgs e)
        {
            var exp = Expressionable.Create<VUser>();

            if (cbbSearchCondition.SelectedItem.ToString() == "创建时间")
            {
                DateTime start = DateTime.Parse(dtStartTime.Value.ToString("yyyy-MM-dd") + " 00:00:00");
                DateTime end = DateTime.Parse(dtStartTime.Value.ToString("yyyy-MM-dd") + " 23:59:59");
                exp.Or(ut => ut.CreateTime >= start && ut.CreateTime <= end);
            }
            else if (cbbSearchCondition.SelectedItem.ToString() == "修改时间")
            {
                DateTime start = DateTime.Parse(dtStartTime.Value.ToString("yyyy-MM-dd") + " 00:00:00");
                DateTime end = DateTime.Parse(dtStartTime.Value.ToString("yyyy-MM-dd") + " 23:59:59");
                exp.Or(ut => ut.LastUpdateTime >= start && ut.LastUpdateTime <= end);
            }
            else
            {
                exp.OrIF(!string.IsNullOrWhiteSpace(txtCondition.Text), ut =>
                ut.Account.Contains(txtCondition.Text) ||
                ut.Password.Contains(txtCondition.Text) ||
                ut.UserTypeName.Contains(txtCondition.Text) ||
                ut.Remark.Contains(txtCondition.Text) ||
                ut.StatusName.Contains(txtCondition.Text) ||
                ut.CreateUserName.Contains(txtCondition.Text) ||
                ut.LastUpdateUserName.Contains(txtCondition.Text)
                );
            }

            var query = SqlSugarHelper.Db.Queryable<VUser>().Where(exp.ToExpression()).OrderByDescending(ut => ut.UserId);
            int count = query.Count();
            ucPager1.TotalPage = count % ucPager1.PageSize == 0 ? count / ucPager1.PageSize : count / ucPager1.PageSize + 1;

            dataGridView1.DataSource = query.Skip((ucPager1.Page - 1) * ucPager1.PageSize).Take(ucPager1.PageSize)
                .ToList();

            dataGridView1.Columns["UserId"].HeaderText = "用户编号";
            dataGridView1.Columns["Account"].HeaderText = "账号";
            dataGridView1.Columns["Password"].HeaderText = "密码";
            dataGridView1.Columns["UserTypeId"].HeaderText = "用户类型编号";
            dataGridView1.Columns["UserTypeName"].HeaderText = "用户类型名称";
            dataGridView1.Columns["Remark"].HeaderText = "备注";
            dataGridView1.Columns["Status"].HeaderText = "状态";
            dataGridView1.Columns["StatusName"].HeaderText = "状态";
            dataGridView1.Columns["CreateUserId"].HeaderText = "创建人";
            dataGridView1.Columns["CreateUserName"].HeaderText = "创建人";
            dataGridView1.Columns["CreateTime"].HeaderText = "创建时间";
            dataGridView1.Columns["LastUpdateUserId"].HeaderText = "修改人";
            dataGridView1.Columns["LastUpdateUserName"].HeaderText = "修改人";
            dataGridView1.Columns["LastUpdateTime"].HeaderText = "修改时间";

            dataGridView1.Columns["UserTypeId"].Visible = false;
            dataGridView1.Columns["Status"].Visible = false;
            dataGridView1.Columns["CreateUserId"].Visible = false;
            dataGridView1.Columns["LastUpdateUserId"].Visible = false;

            dataGridView1.Columns["CreateTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";
            dataGridView1.Columns["LastUpdateTime"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";
        }

        private void cbbSearchCondition_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            if (comboBox.SelectedItem.ToString().Contains("时间"))
            {
                panelSearchCondition.Controls.Clear();
                txtCondition = null;

                dtStartTime = new DateTimePicker();
                int y = (panelSearchCondition.Height - dtStartTime.Height) / 2;
                dtStartTime.Location = new Point(0, y);
                panelSearchCondition.Controls.Add(dtStartTime);

                dtEndTime = new DateTimePicker();
                dtEndTime.Location = new Point(dtStartTime.Width + 10, y);
                panelSearchCondition.Controls.Add(dtEndTime);
            }
            else
            {
                panelSearchCondition.Controls.Clear();
                dtStartTime = null;
                dtEndTime = null;

                txtCondition = new TextBox();
                int y = (panelSearchCondition.Height - txtCondition.Height) / 2;
                txtCondition.Width = panelSearchCondition.Width - 20;
                txtCondition.Location = new Point(0, y);
                panelSearchCondition.Controls.Add(txtCondition);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            ucPager1.Page = 1;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Enter)
            {
                btnSearch.PerformClick();
                return true; // 表示消息已被处理
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            UserAddEditFrm frm = new UserAddEditFrm(0);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                btnSearch.PerformClick();
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count != 1)
            {
                MessageBox.Show("请选择一条数据进行修改！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
            var model = SqlSugarHelper.Db.Queryable<User>().Single(item => item.UserId == id);
            if (model != null && model.Status == 1)
            {
                MessageBox.Show("不能修改已删除的数据！请先启用数据！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            UserAddEditFrm frm = new UserAddEditFrm(id);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                btnSearch.PerformClick();
            }
        }

        private bool DeleteAndEnabled(bool isDelete = true)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                string msg = isDelete ? "删除" : "启用";
                MessageBox.Show($"请选择要{msg}的数据！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            List<User> models = new List<User>();
            foreach (DataGridViewRow item in dataGridView1.SelectedRows)
            {
                int id = int.Parse(item.Cells[0].Value.ToString());
                var model = SqlSugarHelper.Db.Queryable<User>().Single(ut => ut.UserId == id);
                if (isDelete)
                {
                    if (model.Status == 1) continue;
                    model.Status = 1;
                }
                else
                {
                    if (model.Status == 0) continue;
                    model.Status = 0;
                }
                models.Add(model);
            }

            if (models.Count == 0)
            {
                string msg1 = isDelete ? "禁用" : "正常";
                string msg2 = isDelete ? "删除" : "启用";
                MessageBox.Show($"您选择的数据是{msg1}的，不必{msg2}！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            int row = SqlSugarHelper.Db.Updateable(models).ExecuteCommand();
            if (row <= 0)
            {
                string msg = isDelete ? "删除" : "启用";
                MessageBox.Show($"{msg}数据失败，请联系管理员！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            btnSearch.PerformClick();
            return true;
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DeleteAndEnabled(true);
        }

        private void btnEnabled_Click(object sender, EventArgs e)
        {
            DeleteAndEnabled(false);
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 7)
            {
                if (e.Value != null && e.Value.ToString() == "禁用") e.CellStyle.ForeColor = Color.DarkRed;
            }
        }
    }
}
